<?php

require_once('user.class.php');

class Login extends User{

	var $login = false;
	
	//statische vars
	var $instance = null;
	
	function getInstance() {
		if($instance == null) {
		  $instance = new Login;
		}
		return $instance;
	}
	
	function init($usertable) {
		global $db;
		
		if($this->username == null)
			$this->username= $_SESSION['username'];
		if($this->passwd == null)
			$this->passwd = $_SESSION['passwd'];
		$this->usertable = $usertable;
		$this->login();
	}
	
	function login() {
		global $db;
		
		 if(!$this->passwd == null && !$this->username == null) {
		
			$numrows = $db->getOne("SELECT count(*) FROM ". $this->usertable ." WHERE username = '". addslashes($this->username) ."' and passwd = '". $this->passwd ."'");
			
			if($numrows == 1) {
			  $this->login = true;
			  $_SESSION['username']=$this->username;
			  $_SESSION['passwd']=$this->passwd;
			  User::initByUsername($this->username);
			}
			
		}
		
		return $this->login;
	}
	
	function loginByUsername($username, $passwd) {
		$this->setUsername($username);
		$this->setPasswd($passwd);
		$this->login();
	}
	
	function loginByHash($hash) {
		$this->setHash($hash);
		global $db;
		
		 if(!$this->hash == null) {
		
			$numrows = $db->getOne("SELECT count(*) FROM ". $this->usertable ." WHERE hash = '". addslashes($this->hash) ."'");
			
			if($numrows == 1) {
			  $this->login = true;
			  User::initByHash($this->hash);
			  $_SESSION['username']=$this->username;
			  $_SESSION['passwd']=$this->passwd;
			}
			
		}
		
		return $this->login;
	}
	
	function isLogin() {
		return $this->login;
	}
	
	function update() {
		global $db;
		
		User::update();
		
		if($this->isLogin()==true) {
			$_SESSION['username']=$this->username;
			$_SESSION['passwd']=$this->passwd;
		}
	}
	
	function logOut() {
		$_SESSION['username']="";
		$_SESSION['passwd']="";
		$this->login = false;
		$this->username = "";
		$this->passwd = "";
	}

}
